package com.ruoyi.mateTemplate.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mateTemplate.domain.ProductTemplate;
import com.ruoyi.mateTemplate.domain.ProductTemplateModel;
import com.ruoyi.mateTemplate.mapper.TemplateMapper;
import com.ruoyi.mateTemplate.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author
 * @Version 1.0
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    TemplateMapper templateMapper;

    @Override
    public int insertTemplate(ProductTemplate productTemplate) {
        int num = 0;
        Long deptId = SecurityUtils.getDeptId();
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("productId", productTemplate.getProductId());
        resMap.put("deptId", deptId);
        try {
            ProductTemplate productTemplates = templateMapper.selectProductTemplate(resMap);
            if (productTemplates != null) {
                templateMapper.removeTemplate(productTemplates.getTemplateId());
                templateMapper.removeTemplateModel(productTemplates.getTemplateId());
                productTemplate.setDeptId(deptId);
                num = templateMapper.insertTemplate(productTemplate);
                if (productTemplate.getProductTemplateModels() != null) {
                    for (ProductTemplateModel productTemplateModel : productTemplate.getProductTemplateModels()) {
                        productTemplateModel.setTemplateId(productTemplate.getTemplateId());
                        productTemplateModel.setDeptId(deptId);
                        templateMapper.insertTemplateModel(productTemplateModel);
                    }
                }
            } else {
                productTemplate.setDeptId(deptId);
                num = templateMapper.insertTemplate(productTemplate);
                if (productTemplate.getProductTemplateModels() != null) {
                    for (ProductTemplateModel productTemplateModel : productTemplate.getProductTemplateModels()) {
                        productTemplateModel.setTemplateId(productTemplate.getTemplateId());
                        productTemplateModel.setDeptId(deptId);
                        templateMapper.insertTemplateModel(productTemplateModel);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return num;
    }

    @Override
    public ProductTemplate selectTemplate(Long productId) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("productId", productId);
        resMap.put("deptId", SecurityUtils.getDeptId());
        return templateMapper.selectAllProductTemplate(resMap);
    }


}
